﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iPhotoUploader.Library;

namespace iPhotoUploader.GUI
{
    public partial class CreateEventForm : Form
    {
        public bool Edit;
        public string EventName { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        activeexposure.iPhoto active = new activeexposure.iPhoto();
        List<activeexposure.CategoryLight> Categories = new List<activeexposure.CategoryLight>();

        public CreateEventForm()
        {
            InitializeComponent();
        }

        private void CreateEventForm_Load(object sender, EventArgs e)
        {
            LoadRegion();
            LoadFamilyItems();
            LoadCategories();

            if (Edit && Settings.EventId != null)
            {
                
                activeexposure.EventLight evt = active.GetEventByID(new Guid(Settings.EventId));
                txtEventName.Text = evt.Name;
                dtpStartDate.Value = evt.StartDate;
                dtpEndDate.Value = evt.EndDate;
                txtShortDescription.Text = evt.ShortDescription;
                txtLongDescription.Text= evt.LongDescription;
                
                ddlRegion.SelectedValue = evt.Region;
                ddlRegion_SelectedIndexChanged(sender, e);
                
                ddlCountry.SelectedValue = evt.Country;
                ddlCountry_SelectedIndexChanged(sender, e);

                ddlState.SelectedValue = evt.State;
                ddlState_SelectedIndexChanged(sender, e);
                
                ddlCity.SelectedValue = evt.City;
                
                txtLocation.Text = evt.Location;
                ddlFamily.SelectedValue = evt.Family;

                foreach (var cat in evt.Categories)
                {
                    
                    lstSelectedCategories.Items.Add(cat.Id.ToString(), cat.ParentName + "\\" + cat.Name, cat.Id.ToString());
                }
            }
            else
            {
                txtEventName.Text = CleanEventName(EventName);

                if (StartDate != DateTime.MinValue)
                    dtpStartDate.Value = StartDate;

                if (EndDate != DateTime.MinValue)
                    dtpEndDate.Value = EndDate;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                activeexposure.EventLight evt = new activeexposure.EventLight
                {
                    Name = txtEventName.Text,
                    ParentId = new Guid(),
                    StartDate = dtpStartDate.Value,
                    EndDate = dtpEndDate.Value,
                    ShortDescription = txtShortDescription.Text,
                    LongDescription = txtLongDescription.Text,
                    Region = GetDDLValue(ddlRegion),
                    Country = GetDDLValue(ddlCountry),
                    City = GetDDLValue(ddlCity),
                    State = GetDDLValue(ddlState),
                    Location = txtLocation.Text,
                    Family = GetFamilyValue(),
                    Categories = GetCategories()
                };

                string id = string.Empty;

                if (Edit)
                {
                    evt.Id = new Guid(Settings.EventId);
                    id = active.UpdateEvent(evt);

                }
                else
                    id = active.CreateEvent(evt);

                Settings.EventId = id;
                Settings.EventName = txtEventName.Text;


                ((MainForm)Application.OpenForms["MainForm"]).SetLabel(Settings.EventName);
                

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected string CleanEventName(string originalEventName)
        {
            string newEventName = originalEventName;
            if (originalEventName.Contains(":"))
            {
                int index = originalEventName.IndexOf(":");
                if (index > -1)
                {
                    index++;
                    newEventName = originalEventName.Substring(index, originalEventName.Length - index);
                }
            }

            return newEventName.Trim();
        }

        protected string GetDDLValue(ComboBox cmb)
        {
            if (cmb.SelectedValue == null)
                return cmb.Text;
            else
                return cmb.SelectedValue.ToString();

        }

        protected activeexposure.CategoryLight[] GetCategories()
        {
            List<activeexposure.CategoryLight> categories = new List<activeexposure.CategoryLight>();
            foreach (ListViewItem item in lstSelectedCategories.Items)
            {
                categories.Add(new activeexposure.CategoryLight{ Id = new Guid(item.ImageKey)});
            }

            return categories.ToArray();
        }

        protected int GetFamilyValue()
        {
            if (ddlFamily.SelectedValue != null)           
            {
                return Int32.Parse(ddlFamily.SelectedValue.ToString());                
            }

            return 0;
        }

        protected void LoadFamilyItems()
        {
            try
            {
                Dictionary<string, string> values = new Dictionary<string, string>();
                values.Add("0", "- Select -");
                values.Add("1", "Ryans");
                values.Add("2", "Hardens");

                ddlFamily.DisplayMember = "Value";
                ddlFamily.ValueMember = "Key";
                ddlFamily.DataSource = new BindingSource(values, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected void LoadRegion()
        {
            try
            {
                string[] regions = active.GetDistinctRegions();

                Dictionary<string, string> values = new Dictionary<string, string>();
                values.Add("0", "- Select -");
                foreach (string region in regions)
                {
                    values.Add(region, region);
                }

                ddlRegion.DisplayMember = "Value";
                ddlRegion.ValueMember = "Key";
                ddlRegion.DataSource = new BindingSource(values, null);
                ddlRegion.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected void LoadCategories()
        {
            trCategories.Nodes.Clear();
            foreach (activeexposure.CategoryLight category in active.GetCategories())
            {
                trCategories.Nodes.Add(category.Id.ToString(), category.Name, category.Id.ToString());

                if (category.SubCategories.Count() > 0)
                {
                    TreeNode tn = trCategories.Nodes.Find(category.Id.ToString(), true)[0];
                    foreach (activeexposure.CategoryLight sub in category.SubCategories)
                    {
                        tn.Nodes.Add(sub.Id.ToString(), sub.Name, sub.Id.ToString());
                    }
                }
            }
        }

        private void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlRegion.SelectedValue.ToString() != "0")
                {
                    string region = ddlRegion.SelectedValue.ToString();
                    string[] countries = active.GetDistinctCountries(region);

                    Dictionary<string, string> values = new Dictionary<string, string>();
                    values.Add("0", "- Select -");
                    foreach (string country in countries)
                    {
                        values.Add(country, country);
                    }

                    ddlCountry.DisplayMember = "Value";
                    ddlCountry.ValueMember = "Key";
                    ddlCountry.DataSource = new BindingSource(values, null);
                    ddlCountry.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlCountry.SelectedValue.ToString() != "0")
                {
                    string country = ddlCountry.SelectedValue.ToString();
                    string[] states = active.GetDistinctStates(country);

                    if (states[0] != null)
                    {
                        Dictionary<string, string> values = new Dictionary<string, string>();
                        values.Add("0", "- Select -");
                        foreach (string state in states)
                        {
                            values.Add(state, state);
                        }

                        ddlState.DisplayMember = "Value";
                        ddlState.ValueMember = "Key";
                        ddlState.DataSource = new BindingSource(values, null);
                        ddlState.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlState.SelectedValue.ToString() != "0")
                {
                    string state = ddlState.SelectedValue.ToString();
                    string[] cities = active.GetDistinctCities(state);

                    if (cities[0] != null)
                    {
                        Dictionary<string, string> values = new Dictionary<string, string>();
                        values.Add("0", "- Select -");
                        foreach (string city in cities)
                        {
                            values.Add(city, city);
                        }

                        ddlCity.DisplayMember = "Value";
                        ddlCity.ValueMember = "Key";
                        ddlCity.DataSource = new BindingSource(values, null);
                        ddlCity.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSelectCategory_Click(object sender, EventArgs e)
        {
            if (trCategories.SelectedNode != null)
            {
                TreeNode tn = trCategories.SelectedNode;
                lstSelectedCategories.Items.Add(tn.ImageKey, tn.FullPath, tn.ImageKey);
            }
        }

        private void btnRemoveCategory_Click(object sender, EventArgs e)
        {
            if (lstSelectedCategories.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in lstSelectedCategories.SelectedItems)
                {
                    lstSelectedCategories.Items.Remove(item);
                }
            }
        }

        private void trCategories_MouseUp(object sender, MouseEventArgs e)
        {
             if(e.Button == MouseButtons.Right)
              {
                trCategories.SelectedNode = trCategories.GetNodeAt(e.X, e.Y);

                if(trCategories.SelectedNode != null)
                {
                    contextMenuStrip1.Show(trCategories, e.Location);
                }
              }
        }

        private void addNewSubCategory_Click(object sender, EventArgs e)
        {
            Category form = new Category();
            form.ParentId = new Guid(trCategories.SelectedNode.ImageKey);
            form.ShowDialog();
        }

        private void addNewCategory_Click(object sender, EventArgs e)
        {
            Category form = new Category();
            form.ShowDialog();
        }

        public void RefreshCategories()
        {
            LoadCategories();
        }

    }
}
